package com.example.testjsbridgedemo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.testjsbridgedemo.util.AssetUtil;
import com.example.testjsbridgedemo.util.ToastUtil;
import com.example.testjsbridgedemo.view.VueWebView;
import com.gzsll.jsbridge.WVJBWebView;


public class MainActivity extends Activity {

    private VueWebView webView;
    private EditText etRegisterFunction;
    private EditText etCallFunction;
    private EditText etCallParams;
    private EditText etLoadUrl;
    private Button btnRegister;
    private Button btnCall;
    private Button btnLoad;
    private Button btnTestSendQuestion;

    private Boolean isShowPanel = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();
        setupWebView();
        setupClickListeners();
    }

    private void initViews() {
        webView = findViewById(R.id.webView);
        etRegisterFunction = findViewById(R.id.etRegisterFunction);
        etCallFunction = findViewById(R.id.etCallFunction);
        etCallParams = findViewById(R.id.etCallParams);
        etLoadUrl = findViewById(R.id.etLoadUrl);
        btnRegister = findViewById(R.id.btnRegister);
        btnCall = findViewById(R.id.btnCall);
        btnLoad = findViewById(R.id.btnLoad);
        btnTestSendQuestion = findViewById(R.id.btnTestSendQuestion);
        LinearLayout panelLayout = findViewById(R.id.ll_panel);

        Button showBtn = findViewById(R.id.btn_show_btns);
        showBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowPanel = !isShowPanel;
//                ToastUtil.show(MainActivity.this, isShowPanel ? "展示面板" : "隐藏面板");
                showBtn.setText(isShowPanel ? "隐藏面板" : "展示面板");
                panelLayout.setVisibility(isShowPanel ? View.VISIBLE : View.GONE);
            }
        });

        findViewById(R.id.btnRegisterUpdateStatus).setOnClickListener(v -> {
            webView.registerHandler("phonebridge", new WVJBWebView.WVJBHandler() {
                @Override
                public void request(Object data, WVJBWebView.WVJBResponseCallback callback) {
                    /**
                     * {
                     *      type: "sendStatusToNative",
                     *      status:"1“,
                     *      appKey:"expert"
                     *  }
                     */
                    String result = "H5调用了" + "phonebridge 方法" + "，参数：" + data;
                    Log.e("TAG", " webView.registerHandler(phonebridge) result = " + result);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
                        }
                    });
                    callback.callback("sendStatusToNative evaluate success");
                }
            });
        });

        findViewById(R.id.btnTestSendQuestion).setOnClickListener(v -> testSendQuestion());
        findViewById(R.id.btnTestChangeSession).setOnClickListener(v -> testChangeSession());
        findViewById(R.id.btnTestCreateSession).setOnClickListener(v -> testCreateSession());
        findViewById(R.id.btnTestStopIdentify).setOnClickListener(v -> testStopIdentify());
//        findViewById(R.id.btnSendStatusToH5).setOnClickListener(v -> sendStatusToH5());
    }

    private void setupWebView() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDefaultTextEncodingName("utf-8");
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);
        settings.setDatabaseEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        webView.requestFocus();
        webView.loadUrl("file:///android_asset/test.html");
    }

    private void setupClickListeners() {
        // 注册函数供H5调用
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String functionName = etRegisterFunction.getText().toString().trim();
                if (functionName.isEmpty()) {
                    ToastUtil.show(MainActivity.this, "请输入函数名");
                    return;
                }

                webView.registerHandler(functionName, new WVJBWebView.WVJBHandler() {
                    @Override
                    public void request(Object data, WVJBWebView.WVJBResponseCallback callback) {
                        String result = "H5调用了" + functionName + "，参数：" + data;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
                            }
                        });
                        callback.callback("Native返回数据：" + functionName + "执行成功");
                    }
                });
                Toast.makeText(MainActivity.this, "函数" + functionName + "注册成功", Toast.LENGTH_SHORT).show();
            }
        });

        // 调用H5函数
        btnCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String functionName = etCallFunction.getText().toString().trim();
                String params = etCallParams.getText().toString().trim();
                if (functionName.isEmpty()) {
                    Toast.makeText(MainActivity.this, "请输入要调用的H5函数名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (params.isEmpty()) {
                    Toast.makeText(MainActivity.this, "请输入JSON参数", Toast.LENGTH_SHORT).show();
                    return;
                }
                doCallHandler(functionName, params);
            }
        });

        // 加载URL
        btnLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = etLoadUrl.getText().toString().trim();
                if (url.isEmpty()) {
                    Toast.makeText(MainActivity.this, "请输入URL地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                webView.loadUrl(url);
            }
        });
    }

    private void testSendQuestion(){
        String content = AssetUtil.getFileContent(MainActivity.this, "send_question.json");
        etCallFunction.setText(WebJs.DATA.JAVA2H5_CHANNEL);
        etCallParams.setText(content);
        ToastUtil.showDefaultShort(this, "请手动点击 调用H5函数 的按钮");
    }

    private void testChangeSession(){
        String content = AssetUtil.getFileContent(MainActivity.this, "change_question.json");
        etCallFunction.setText(WebJs.DATA.JAVA2H5_CHANNEL);
        etCallParams.setText(content);
    }

    private void testCreateSession(){
        String content = AssetUtil.getFileContent(MainActivity.this, "create_session.json");
        etCallFunction.setText(WebJs.DATA.JAVA2H5_CHANNEL);
        etCallParams.setText(content);
    }

    private void testStopIdentify(){
        String content = AssetUtil.getFileContent(MainActivity.this, "stop_identify.json");
        etCallFunction.setText(WebJs.DATA.JAVA2H5_CHANNEL);
        etCallParams.setText(content);
    }

//    private void sendStatusToH5(){
//        String content = AssetUtil.getFileContent(MainActivity.this, "send_status_to_h5.json");
//        etCallFunction.setText(WebJs.DATA.JAVA2H5_CHANNEL);
//        etCallParams.setText(content);
//    }

    private void doCallHandler(String functionName, String params){
        webView.callHandler(functionName, params, new WVJBWebView.WVJBResponseCallback() {
            @Override
            public void callback(Object data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "收到H5返回：" + data, Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }
}